package org.jetlinks.pro.messaging.rabbitmq.command.admin;

import com.alibaba.fastjson.JSON;
import org.jetlinks.pro.datasource.Command;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;

import java.net.URI;

/**
 * 管理命令,用于进行RabbitMQ相关管理功能,比如创建用户{@link CreateUser},创建权限{@link SetPermission}等功能
 *
 * @param <R>
 * @author zhouhao
 * @see CreateUser
 * @see GetUsers
 * @since 1.10
 */
public abstract class AdminCommand<R> implements Command<R> {

    public R doRequest(WebClient webClient) {
        HttpMethod method = method();

        WebClient.RequestBodySpec bodySpec = webClient
            .method(method())
            .uri(uriBuilder -> {
                URI uri = uriBuilder.build();
                return uri.resolve(api());
            })
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON);

        switch (method) {
            case GET:
            case DELETE:
                break;
            default:
                bodySpec.bodyValue(JSON.toJSONString(requestBody()));
        }

        return convert(bodySpec.retrieve());
    }

    public abstract String api();

    public abstract HttpMethod method();

    public abstract R convert(WebClient.ResponseSpec responseSpec);

    public Object requestBody() {
        return this;
    }
}
